package imoney.client.handler;

import imoney.client.gwt.GwtUtils;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.TextBox;

public class CommaKeyHandler implements KeyPressHandler {

	TextBox textB1;
	String content;
	FlexTable table;
	int row;

	/**
	 * This handler creates a new TextBox when the comma key is pressed.
	 * The focus is set to the new TextBox.
	 * 
	 * @param text : the textBox to handle.
	 * @param prefilContent : the prefil content of this textBox.
	 * @param table : the table in which the new textbox will be displayed.
	 * @param row : the row of the current textBox (on which this handler applies).
	 */
	public CommaKeyHandler(TextBox text, String prefilContent, FlexTable table, int row) {
		textB1 = text;
		content = prefilContent;
		this.table = table;
		this.row = row;
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getCharCode() == (',')) {
			String currentText = textB1.getText();
			if (currentText.endsWith(",")) {
				currentText = currentText.substring(0, currentText.length()-1);
				textB1.setText(currentText);
			}
			
			// pack event source textbox, it wont be written anymore
			textB1.setVisibleLength(textB1.getText().length());
			
			// create a new textfield for the name of a new person
			int col = table.getCellCount(row);
			TextBox newText = new TextBox();
			newText.addBlurHandler(new DeleteOnBlur(newText, table));
			newText.addFocusHandler(new FocusEmptyText(newText, content));
			newText.addKeyPressHandler(new CommaKeyHandler(newText, content, table, row));
			table.setWidget(row, col, newText);
			newText.setFocus(true);
		}
	}

	/**
	 * Handler that removes the textBox if it was not populated when focus leaves.
	 * @author Arnaud PELOQUIN
	 */
	private class DeleteOnBlur implements BlurHandler {
		TextBox textbox;
		FlexTable table;
		
		/**
		 * Handler that removes the textBox if it was not populated when focus leaves.
		 * @author Arnaud PELOQUIN
		 */
		public DeleteOnBlur(TextBox text, FlexTable table) {
			textbox = text;
			this.table = table;
		}
		
		@Override
		public void onBlur(BlurEvent event) {
			if (textbox.getText().equals("") || textbox.getText().startsWith(",")) {
				int col = GwtUtils.getWidgetCol(table, textbox, row);
				System.out.println("comma key handler column of blurred textbox: "+col);
				if (col != table.getCellCount(row)-1){ // find a better way to do it because it blows if a non-text field is added to the right..
					table.remove(textbox);
				}
				else{
					textbox.setText(content);
				}
			}
			textbox.setVisibleLength(textbox.getText().length());
		}
		
	}

}
